package algorithm.data;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 位置文件读取工具类
 * @author letere
 * @since  2020-12-25 11:04
 */
public class PositionUtil {

    /**
     * 创建距离矩阵
     * @return 距离矩阵
     */
    public static int[][] getDistanceMatrix(String filePath) {
        // 读取文件
        List<String> texts = readFile(filePath);
        // 创建数组
        int citySize = texts.size();
        int[][] distanceMatrix = new int[citySize][citySize];
        // 填充数据
        for(int i=0; i<citySize; i++) {
            distanceMatrix[i][i] = 0;
            for (int j=i+1; j<citySize; j++) {
                //按空格分割字符串
                String[] city1 = texts.get(i).split(" ");
                String[] city2 = texts.get(j).split(" ");
                //两点距离公式（整数方便查看）
                double distance = Math.pow((Integer.parseInt(city1[1]) - Integer.parseInt(city2[1])), 2) + Math.pow((Integer.parseInt(city1[2]) - Integer.parseInt(city2[2])), 2);
                distanceMatrix[i][j] = (int) Math.sqrt(distance);
                distanceMatrix[j][i] = distanceMatrix[i][j];
            }
        }
        return distanceMatrix;
    }

    /**
     * 读取文件内容，将每一行文本封装为字符串集合
     * @return 文件内容
     */
    private static List<String> readFile(String filePath){
        List<String> texts = new ArrayList<>();
        BufferedReader br = null;
        // 读取文件
        try {
            br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
            String text;
            while((text = br.readLine()) != null) {
                if (text.startsWith("#")) {
                    continue;
                }
                texts.add(text);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭流
            try {
                br.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return texts;
    }
}
